<template>
  <el-card shadow="hover">
    <div class="header d-flex justify-content-between align-items-center">
      <h3>商品类别管理</h3>
      <el-button type="primary" @click="openAddDialog">新增</el-button>
    </div>
    <el-table :data="products" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="category" label="分类" />
      <el-table-column prop="subcategory" label="子分类" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openEditDialog(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增产品分类对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增产品分类" width="500px">
      <el-form :model="newProduct" :rules="addRules" ref="addForm">
        <el-form-item label="分类" prop="category">
          <el-input v-model="newProduct.category" />
        </el-form-item>
        <el-form-item label="子分类" prop="subcategory">
          <el-input v-model="newProduct.subcategory" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addProduct">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑分类" width="500px">
      <el-form :model="editProduct" :rules="editRules" ref="editForm">
        <el-form-item label="分类" prop="category">
          <el-input v-model="editProduct.category" />
        </el-form-item>
        <el-form-item label="子分类" prop="subcategory">
          <el-input v-model="editProduct.subcategory" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editProductInfo">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// Reactive state for products
const products = ref([]);

// Reactive state for add dialog
const addDialogVisible = ref(false);
const newProduct = ref({
  category: '',
  subcategory: ''
});
const addRules = reactive({
  category: [
    { required: true, message: '分类不能为空', trigger: 'blur' }
  ],
  subcategory: [
    { required: true, message: '子分类不能为空', trigger: 'blur' }
  ]
});
const addForm = ref(null); // Add form reference for validation

// Reactive state for edit dialog
const editDialogVisible = ref(false);
const editProduct = ref({
  id: '',
  category: '',
  subcategory: ''
});
const editRules = reactive({
  category: [
    { required: true, message: '分类不能为空', trigger: 'blur' }
  ],
  subcategory: [
    { required: true, message: '子分类不能为空', trigger: 'blur' }
  ]
});
const editForm = ref(null); // Edit form reference for validation

// Load products from the server
const loadProducts = () => {
  axios.get('http://localhost:8080/product_list/load')
      .then(response => {
        products.value = response.data;
      })
      .catch(error => {
        console.error('加载产品分类列表失败:', error);
        ElMessage.error('加载产品分类列表失败');
      });
};

// Open add product dialog
const openAddDialog = () => {
  addDialogVisible.value = true;
  // Reset form fields and clear validation
  resetForm(addForm);
};

// Add new product to the server
const addProduct = () => {
  addForm.value.validate((valid) => {
    if (valid) {
      axios.post('http://localhost:8080/product_list/insert', newProduct.value)
          .then(() => {
            ElMessage.success('新增产品分类成功');
            loadProducts(); // Refresh the product list
            addDialogVisible.value = false;
            resetForm(addForm); // Clear form fields and validation
          })
          .catch(error => {
            console.error('新增产品分类失败:', error);
            ElMessage.error('新增产品分类失败');
          });
    } else {
      // Form validation failed
      return false;
    }
  });
};

// Open edit product dialog with product data
const openEditDialog = (product) => {
  editProduct.value = { ...product };
  editDialogVisible.value = true;
  // Reset form fields and clear validation
  resetForm(editForm);
};

// Edit product info on the server
const editProductInfo = () => {
  editForm.value.validate((valid) => {
    if (valid) {
      axios.put(`http://localhost:8080/product_list/update`, editProduct.value)
          .then(() => {
            ElMessage.success('编辑产品分类成功');
            loadProducts(); // 刷新产品列表
            editDialogVisible.value = false;
            resetForm(editForm); // 清除表单字段和验证
          })
          .catch(error => {
            console.error('编辑产品分类失败:', error);
            ElMessage.error('编辑产品分类失败');
          });
    } else {
      // 表单验证失败
      console.error('表单验证失败');
      return false;
    }
  });
};

// Delete product from the server
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该产品分类吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(() => {
        axios.delete(`http://localhost:8080/product_list/delete/${id}`)
            .then(() => {
              ElMessage.success('删除成功');
              loadProducts(); // Refresh the product list
            })
            .catch(error => {
              console.error('删除产品分类失败:', error);
              ElMessage.error('删除产品分类失败');
            });
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// Helper function to reset form fields and clear validation
const resetForm = (formRef) => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// Load products on component mount
onMounted(() => {
  loadProducts();
});
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-card {
  padding: 20px;
  border-radius: 10px;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-table .el-button {
  margin-right: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-dialog {
  border-radius: 10px;
}

.el-input {
  border-radius: 5px;
}
</style>
